package com.sso.action.sys;


import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import com.sso.manager.SysMenuResourceViewManager;
import com.sso.shiro.RealmManager;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.config.Ini;
import org.apache.shiro.config.Ini.Section;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.filter.mgt.DefaultFilterChainManager;
import org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver;
import org.apache.shiro.web.servlet.AbstractShiroFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.sso.action.BaseAction;
import com.sso.common.enums.FlagStatus;
import com.sso.common.enums.SysResourceEnum;
import com.sso.entity.SysResource;
import com.sso.exception.SelectException;
import com.sso.manager.SysResourceManager;

@Controller
@RequestMapping("sys")
public class SysAction extends BaseAction{
	@Autowired
	private SysResourceManager resManager;
	@Autowired
	private ShiroFilterFactoryBean shiroFileterFactoryBean;
	@Autowired
	private SysMenuResourceViewManager menuResourceViewManager;
	
	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@RequestMapping("index")
	public ModelAndView gotoIndex(){
		ModelAndView view = new ModelAndView("/manager/index");
		return view;
	}
	
	
	/**
	 * 刷新资源文件
	 */
	@RequestMapping("refreshResource")
	public void refreshResource(HttpServletResponse response) {
		String packageName = "com.sso.action";
		String packageDirName = packageName.replace(".", "/");
		try {
			Enumeration<URL> dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName);
			// 迭代此 Enumeration
			List<SysResource> resList = new ArrayList<SysResource>();
			while (dirs.hasMoreElements()) {
				URL url = dirs.nextElement();
				File file = new File(url.getFile());
				// 把此目录下的所有文件列出
				File[] fileList = file.listFiles() ;
				resManager.getAllRefreshResource(packageName,fileList,resList);
			}
			resManager.saveResource(resList);
			this.outputJson(FlagStatus.SUCCESS.value, "刷新成功", response);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			this.outputJson(FlagStatus.SUCCESS.value, "读取异常", response);
		} catch (Exception e) {
			e.printStackTrace();
			this.outputJson(FlagStatus.SUCCESS.value, "刷新失败", response);
		}
	}
	
	/**
	 * 刷新系统权限控制重新加载权限
	 */
	@RequestMapping("refreshAuth")
	public void refreshAuth(){
		try {
		Ini ini = new Ini();
		ini.load("/static/**=anon");
		Section section = ini.getSection(Ini.DEFAULT_SECTION_NAME);
		section.put("/js/**", "anon");
		section.put("/css/**", "anon");
		section.put("/images/**", "anon");
		section.put("/lib/**", "anon");
		Map<String, Object> filterMap = new HashMap<String, Object>();
		filterMap.put("resourceStatus", SysResourceEnum.status.START.key);
		//查询菜单与资源绑定视图
		menuResourceViewManager.getLoadSection(section);
		AbstractShiroFilter shiroFilter = (AbstractShiroFilter) shiroFileterFactoryBean.getObject();
		PathMatchingFilterChainResolver filterChainResolver = (PathMatchingFilterChainResolver) shiroFilter.getFilterChainResolver();
		DefaultFilterChainManager manager = (DefaultFilterChainManager) filterChainResolver.getFilterChainManager();
		manager.getFilterChains().clear();
		shiroFileterFactoryBean.getFilterChainDefinitionMap().clear();  
		shiroFileterFactoryBean.setFilterChainDefinitionMap(section);
        // 重新构建生成  
        Map<String, String> chains = shiroFileterFactoryBean.getFilterChainDefinitionMap();  
        for (Map.Entry<String, String> entry : chains.entrySet()) {  
            String url = entry.getKey();  
            String chainDefinition = entry.getValue().trim().replace(" ", "");  
            manager.createChain(url, chainDefinition);
	    }
        logger.info("**************权限控制加载完毕**************");
		} catch (SelectException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
